package com.jrzh.mvc.controller.sys.admin;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.jrzh.framework.SpringContextUtil;
public class EntityManagerUtil
{
	//保存系统中的EntityManagerFactory
	@PersistenceContext
	private static EntityManagerFactory emf; 
	//使用ThreadLocal来保证EntityManager的线程安全
	private static final ThreadLocal<EntityManager> threadLocal;
	/**初始化*/
	
	static 
	{
		emf = SpringContextUtil.getBean("entityManagerFactory");
		//初始化EntityManagerFactory对象
		threadLocal = new ThreadLocal<EntityManager>();
	}
	//通过ThreadLocal获取EntityManager对象
	public static EntityManager getEntityManager() 
	{
		//获取当前线程关联的EntityManager对象
		EntityManager em = threadLocal.get();
		//如果当前线程关联的EntityManager为null，或没有打开
		if (em == null || !em.isOpen())
		{
			//创建新的EntityManager
			em = emf.createEntityManager();
			threadLocal.set(em);
		}
		return em;
	}
	//关闭EntityManager对象
	public static void closeEntityManager()
	{
		EntityManager em = threadLocal.get();
		threadLocal.set(null);
		if (em != null)
		{
			EntityManagerUtil.closeEntityManager();
		}
	}
	//开始事务
	public static void beginTransaction() 
	{
		getEntityManager().getTransaction().begin();
	}
	//提交事务
	public static void commit() 
	{
		getEntityManager().getTransaction().commit();
	}
	//创建查询
	public static Query createQuery(String jpql)
	{
		return getEntityManager().createNativeQuery(jpql);
	}
	public static Query createUpdate(String jpql)
	{
		return getEntityManager().createQuery(jpql);
	}
}
